<template>
  <div class="page">
    <div
      class="delivery-panel"
      @click="
        toPath(
          '/address/list' +
            (address && address.id ? '?chooseAddressId=' + address.id : '')
        )
      "
    >
      <div class="info-panel" v-if="address">
        <div class="address">
          {{ address.address }}
        </div>
        <div class="userinfo">
          <div class="username">
            {{ address.userName }}{{ address.sex == 0 ? "先生" : "女士" }}
          </div>
          <div class="phone">
            {{ address.phoneNumber }}
          </div>
        </div>
      </div>
      <div class="info-panel" v-else>
        <div class="address">请选择收获地址</div>
      </div>
      <div class="icon">
        <Icon name="arrow" />
      </div>
    </div>
    <div class="shop-panel">
      <div
        class="shop-info"
        v-for="(item, index) in shopCartList"
        :key="item.id"
      >
        <div class="left">
          <div class="img">
            <Image
              width="4rem"
              height="4rem"
              fit="cover"
              position="center"
              :src="baseApi + item.img"
            />
          </div>
          <div class="content">
            <div class="name">{{ item.name }}</div>
            <div class="size">{{ item.num }}</div>
          </div>
        </div>

        <div class="price">{{ item.num * item.price }}</div>
      </div>
      <div style="width: 100%; text-align: end; font-size: 12px">
        共计：<span style="font-size: 18px; font-weight: 600">
          ¥ &nbsp;
          {{ totalPrice }}
        </span>
      </div>
    </div>
    <!-- 备注 -->
    <div>
      <Field
        label="备注"
        v-model="remark"
        type="textarea"
        is-link
        readonly
        @click="toPath('/orderMeal/remark')"
      />
      <Field
        v-model="tablewareNum"
        is-link
        readonly
        label="餐具"
        placeholder="选择餐具数量"
        @click="showTablewareNumPicker = true"
      />
      <Popup v-model:show="showTablewareNumPicker" round position="bottom">
        <Picker
          :columns="tablewareNumChoose"
          @cancel="showTablewareNumPicker = false"
          @confirm="onConfirmTableware"
        />
      </Popup>
    </div>
    <Tabbar :placeholder="true">
      <SubmitBar
        :disabled="
          shopCartList.length == 0 || !notNull(String(address)) || loadingSubmit
        "
        :loading="loadingSubmit"
        :price="totalPrice * 100"
        button-text="立即支付"
        @submit="onSubmit"
      ></SubmitBar>
    </Tabbar>
    <Popup
      style="padding: 64px; border-radius: 5px"
      v-model:show="loadingSubmit"
      :close-on-click-overlay="false"
    >
      <Loading vertical>
        <template #icon>
          <Icon name="star-o" size="24" />
        </template>
        {{ submitLoadingText }}</Loading
      >
    </Popup>
  </div>
</template>
<script lang="ts" setup>
import { getAddress, getDefAddress } from "@/api/address";
import { submitOrder } from "@/api/order";
import { selectShopById } from "@/api/shop";
import { notNull } from "@/utils";
import {
  getCookie,
  getLocalStorage,
  removeCookie,
  removeLocalStorage,
  setCookie,
} from "@/utils/auth";
import enums from "@/utils/enums";
import {
  Icon,
  Image,
  Field,
  Picker,
  Popup,
  Tabbar,
  SubmitBar,
  Loading,
} from "vant";
import { computed, inject, onMounted, ref } from "vue";

const baseApi = process.env.VUE_APP_BASE_API;
const toPath: any = inject("toPath");
/**显示选择餐具数量 */
const showTablewareNumPicker = ref(false);
/**餐具数量选择 */
const tablewareNumChoose = [
  { text: "无需餐具", value: 0 },
  { text: "1份餐具", value: 1 },
  { text: "2份餐具", value: 2 },
  { text: "3份餐具", value: 3 },
  { text: "4份餐具", value: 4 },
  { text: "5份餐具", value: 5 },
  { text: "6份餐具", value: 6 },
  { text: "7份餐具", value: 7 },
  { text: "8份餐具", value: 8 },
];

/**地址 */
const address = ref();
/**购物车 */
const shoppingCart: any = ref();
/**页面展示用的购物车 */
const shopCartList: any = ref([]);
/**备注 */
const remark = ref();
/**餐具数量 */
const tablewareNum = ref("无需餐具");
/**加载支付按钮 */
const loadingSubmit = ref(false);
/**提交订单弹出显示当前进度的文本内容 */
const submitLoadingText = ref("");

/**总金额 */
const totalPrice = computed(() => {
  return shopCartList.value.reduce(
    (pre: any, item: any) => pre + item.num * item.price,
    0
  );
});

onMounted(() => {
  init();
});
/**初始化 */
const init = () => {
  // 选择的地址id
  const chooseAddressId = getCookie(enums.cookie.address.chooseAddressId);
  shoppingCart.value = JSON.parse(
    getLocalStorage(enums.localStorage.order.shoppingCart)
  );

  if (notNull(chooseAddressId)) {
    getAddress(Number(chooseAddressId)).then((res) => {
      address.value = res.data;
    });
  } else {
    // 获取默认地址
    getDefAddress().then((res) => {
      address.value = res.data;
    });
  }

  // 购物车
  const shopIds = Object.keys(shoppingCart.value);
  for (let i = 0; i < shopIds.length; i++) {
    const num = shoppingCart.value[shopIds[i]];
    selectShopById(Number(shopIds[i])).then((res) => {
      if (res.data) {
        shopCartList.value.push({
          id: res.data.id,
          name: res.data.name,
          price: res.data.price,
          img: res.data.img,
          num: num,
        });
      }
    });
  }

  // 获取备注
  remark.value = notNull(getCookie(enums.cookie.order.remark))
    ? getCookie(enums.cookie.order.remark)
    : "";
  // 获取餐具数量
  tablewareNum.value = notNull(getCookie(enums.cookie.order.tablewareNum))
    ? getCookie(enums.cookie.order.tablewareNum)
    : "无需餐具";
};
/**选择几份餐具 */
const onConfirmTableware = (selected: any) => {
  showTablewareNumPicker.value = false;
  tablewareNum.value = selected.selectedOptions[0].text;
  setCookie(enums.cookie.order.tablewareNum, selected.selectedOptions[0].text);
};
/**支付 */
const onSubmit = () => {
  loadingSubmit.value = true;
  submitLoadingText.value = "正在提交数据";
  const tablewareNumer = tablewareNumChoose.filter(
    (item) => item.text === tablewareNum.value
  )[0];
  //提交的数据
  const data = {
    shopCart: JSON.stringify(shopCartList.value),
    totalPrice: totalPrice.value,
    message: remark.value,
    address: address.value.address,
    tablewareNum: tablewareNumer.value,
    phoneNumber: address.value.phoneNumber,
    userName: address.value.userName,
    sex: address.value.sex,
  };
  console.log(data);
  submitOrder(data).then((res: any) => {
    if (res.code == 200) {
      submitLoadingText.value = "支付成功";
      setTimeout(() => {
        loadingSubmit.value = false;
        removeCookie(enums.cookie.order.remark);
      });
    }
  });
  removeLocalStorage(enums.localStorage.order.shoppingCart);
  console.log("支付");
};
</script>

<style lang="less" scoped>
.page {
  padding: 10px;
  min-height: 100%;
  box-sizing: border-box;
  background-color: #f2f2f2;
}
.shop-panel {
  margin-bottom: 10px;
  border-radius: 5px;
  padding: 10px;
  background-color: white;
  .shop-info {
    margin: 5px 0;
    display: flex;
    align-items: center;
    justify-content: space-between;
    gap: 10px;
    .left {
      display: flex;
      align-items: center;
      justify-content: flex-start;
      gap: 8px;
      .img {
        /deep/img {
          border-radius: 16px;
        }
      }
      .content {
        display: flex;
        flex-direction: column;
        gap: 10px;
        .name {
          font-size: 14px;
          font-weight: 600;
        }
        .size {
          font-size: 12px;
          color: #666;
        }
        .size::before {
          content: "x ";
        }
      }
    }
    .price {
      width: 45px;
      font-size: 18px;
      font-weight: 600;
      text-align: right;
    }
    .price::before {
      content: "¥";
    }
  }
}
.delivery-panel {
  margin-bottom: 10px;
  border-radius: 5px;
  padding: 20px;
  background-color: white;
  display: flex;
  justify-content: space-between;
  align-items: center;
  .info-panel {
    .address {
      font-weight: 600;
      font-size: 20px;
    }
    .userinfo {
      display: flex;
      font-size: 13px;
      color: #666;
      gap: 5px;
    }
  }
}
</style>
